package com.das.mechanic_base.mvp.view.camera;

import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

import androidx.fragment.app.Fragment;

import com.das.mechanic_base.R;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.adapter.camera.X3CustomPagerAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.base.X3BasePresenter;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.camera.CameraCloseBean;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StatusBarUtil;
import com.das.mechanic_base.widget.X3CustomViewPager;
import com.google.android.material.tabs.TabLayout;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.imid.swipebacklayout.lib.SwipeBackLayout;

public class X3CameraPhotoActivity extends X3BaseActivity implements TabLayout.BaseOnTabSelectedListener {

    @BindView(R2.id.vp_view)
    X3CustomViewPager vp_view;
    @BindView(R2.id.tb_bottom)
    TabLayout tb_bottom;
    @BindView(R2.id.rl_header)
    FrameLayout rl_header;

    private List<Fragment> mList;

    private String[] title;

    private int currentIndex;

    /**
     * 0 支持多张图片/视频
     * 1 仅支持一张图图片 用于上传头像使用
     * 2 仅支持一张图片或者视频 用于IM发送图片和视屏
     * 3 支持多张图片/相册选取不支持视频 用于初检识别故障灯和车漆 3 是故障灯
     * 4 支持多张图片/相册选取不支持视频 用于初检识别故障灯和车漆 4 是外观
     * 6 支持多张图片/相册选取不支持视频 用于初检贵重物品 5 贵重物品
     */
    private int isAlbum;
    private int normal_select;
    private boolean isStart;

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.x3_activity_camera_photo;
    }

    @Override
    public boolean isTransparent() {
        return false;
    }

    @Override
    protected void initView() {
        setSwpLayout();
        Log.e("SSSS","parent：" + System.currentTimeMillis());
        rl_header.setPadding(0, X3StatusBarUtil.getStatusBarHeight(this),0,0);

        isAlbum = getIntent().getIntExtra("isAlbum", 0);

        normal_select = getIntent().getIntExtra("normal_select", -1);

        vp_view.setScanScroll(false);

        mList = new ArrayList<>();
        mList.add(new X3PhotoFragment());
            //3故障灯  4外观损伤
        if (isAlbum == 0 || isAlbum == 3 || isAlbum == 4 || isAlbum == 5 || isAlbum == 6) {
            tb_bottom.setVisibility(View.VISIBLE);
        }else {
            tb_bottom.setVisibility(View.GONE);
        }

        if (isAlbum == 1) {
            title = new String[]{getString(R.string.x3_take_album)};
        }else if (isAlbum == 3 || isAlbum ==4 || isAlbum == 5 || isAlbum == 6) {
            mList.add(new X3CameraTakeFragment());
            title = new String[]{getString(R.string.x3_take_album), getString(R.string.x3_take_photo)};
        }else {
            mList.add(new X3CameraTakeFragment());
            title = new String[]{getString(R.string.x3_take_album), getString(R.string.x3_take_video), getString(R.string.x3_take_photo)};
        }

        for (int i = 0; i < title.length; i++) {
            tb_bottom.addTab(tb_bottom.newTab().setText(title[i]));
        }

        X3CustomPagerAdapter pagerAdapter = new X3CustomPagerAdapter(getSupportFragmentManager(), mList);
        vp_view.setAdapter(pagerAdapter);


        tb_bottom.addOnTabSelectedListener(this);
        // 默认选中视频
        tb_bottom.post(() -> {
            int index;
            if (normal_select == -1) {
                if (isAlbum == 1) {
                    index = 0;
                }else if (isAlbum == 3 || isAlbum == 4 || isAlbum == 5 || isAlbum == 6) {
                    index = 1;
                }else {
                    index = 2;
                }
            }else {
                index = normal_select;
            }
            isStart = true;
            tb_bottom.getTabAt(index).select();
        });
    }

    private void setSwpLayout(){
        swipeBackLayout.addSwipeListener(new SwipeBackLayout.SwipeListener() {
            @Override
            public void onScrollStateChange(int state, float scrollPercent) {
                if (state == 2){
                    CameraCloseBean closeBean = new CameraCloseBean(2);
                    EventBus.getDefault().post(closeBean);
                }
                Log.e("swipeBackLayout_","state = " + state);
                Log.e("swipeBackLayout_","scrollPercent = " + scrollPercent);
            }

            @Override
            public void onEdgeTouch(int edgeFlag) {
                Log.e("swipeBackLayout_","edgeFlag = " + edgeFlag);
            }

            @Override
            public void onScrollOverThreshold() {
                Log.e("swipeBackLayout_","onScrollOverThreshold = ");
            }
        });
    }

    @Override
    protected X3BasePresenter createPresenter() {
        return null;
    }

    /**
     * 是否隐藏底部导航
     *
     * @param isShow
     */
    public void hideOrShowTabottom(boolean isShow) {
        tb_bottom.animate().translationY(isShow ? 0 : X3ScreenUtils.dipToPx(40, this))
                .setDuration(200).start();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (tb_bottom != null && tb_bottom.getAnimation() != null) {
            tb_bottom.getAnimation().cancel();
        }
        super.onDestroy();
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            setSelectTab(tab);
                        }else {
                            XXPermissions.startPermissionActivity(X3CameraPhotoActivity.this,permissions);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        XXPermissions.startPermissionActivity(X3CameraPhotoActivity.this,permissions);
                    }
                });
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    private void setSelectTab(TabLayout.Tab tab) {
        String tabText = tab.getText().toString();

        if (tabText.contains(getString(R.string.x3_take_album))) {
            currentIndex = 0;
        } else if (tabText.contains(getString(R.string.x3_take_video))) {
            currentIndex = 1;
        } else {
            currentIndex = 2;
        }

        vp_view.setCurrentItem(currentIndex == 0 ? 0 : 1,!isStart);
        isStart = false;
        if (currentIndex != 0) {
            ((X3CameraTakeFragment) mList.get(1)).showVideoOrPicture(currentIndex);
        }
    }

    /**
     * 从相册中选取图片 或者拍照 数据都会从这个方法进入
     * @param cameraBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetPictureOrVideo(CameraBean cameraBean) {
        if (cameraBean == null) {
            return;
        }
        switch ((int) cameraBean.resultCode) {
            //图片或者视频
            case X3Constent.CODE_CAMERA_REQUEST:
            case X3Constent.CODE_GALLERY_REQUEST:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("完整拍摄模式页");
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("完整拍摄模式页");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        CameraCloseBean closeBean = new CameraCloseBean(2);
        EventBus.getDefault().post(closeBean);
    }
}